#settings start
set_browser_dict={"geckodriver_path":"./w/geckodriver.exe","is_headless":True,"time_limit":10}
#settings end
def set_browser(geckodriver_path=None,is_headless=None,time_limit=None):
    if not geckodriver_path==None:
        set_browser_dict['geckodriver_path']=geckodriver_path
    if not is_headless==None:
        set_browser_dict['is_headless']=bool(is_headless)
    if not time_limit==None:
        set_browser_dict['time_limit']=time_limit
from selenium import webdriver
import PIL
import base64
import io
import re
import time
class PDError(Exception):
    def __init__(self,mystr):
        self.mystr=mystr
    def __str__(self):
        return self.mystr
class Dingtalk():
    def __init__(self):
        if set_browser_dict["is_headless"]:
            from selenium.Firefox.options import Options as FirefoxOptions
            options = FirefoxOptions()
            options.add_argument("--headless")
            self.wd=webdriver.Firefox(executable_path=set_browser_dict['geckodriver_path'],options=options)
        else:
            self.wd=webdriver.Firefox(executable_path=set_browser_dict['geckodriver_path'])
        self.wd.get("https://im.dingtalk.com/")
    def get_qr(self):
        try:
            self.wd.find_elements_by_xpath("//*[@id=\"qrcode-login\"]/p/a")[0].click()
        except IndexError:
            raise PDError("Can't locate the refresh button.")
        for i in range(0,set_browser_dict["time_limit"]*10):
            base64code=""
            try:
                base64code+=re.split('''(<img alt="Scan me!" src="|" style="display: block !important;">''',self.wd.page_source,flags=re.S)[1]
            except IndexError:
                time.sleep(0.1)
                continue
            img=PIL.Image.open(io.BytesIO(base64.b64decode(base64code)))
            return img
        raise PDError("Can't locate the QR code image.")
    def get_friends(self):
        friend_list=[]
        try:
            for i in self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[1]/conv-item/div/div[2]/divf/div/p/span")+self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[2]/conv-item/div/div[2]/divf/div/p/span"):
                friend_list.append(i.text)
        except:
            raise PDError("Get contact list failed. It may be that you are not logged in yet.")
        return friend_list
    def get_latest_msg(self,name:str):
        try:
            for i in self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[1]/conv-item/div/div[2]/divf/div/p/span")+self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[2]/conv-item/div/div[2]/divf/div/p/span"):
                if i.text==name:
                    return i.find_element_by_xpath("../../../../div/p/span[4]").text
        except:
            raise PDError("Get the message failed.")
    def send_msg(self,name:str,msg):
        
        for i in self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[1]/conv-item/div/div[2]/divf/div/p/span")+self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[2]/conv-item/div/div[2]/divf/div/p/span"):
            if i.text==name:
                try:
                    self.wd.find_element_by_xpath("//*[@id=\"content-pannel\"]/div/div[3]/div/div[1]/div/textarea").send_keys(msg)
                    self.wd.find_element_by_xpath("//*[@id=\"content-pannel\"]/div/div[3]/div/div[2]/a").click()
                    break
                except:
                    raise PDError("Message sending failed.")
    def send_file(self,name:str,file_path):
        try:
            for i in self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[1]/conv-item/div/div[2]/divf/div/p/span")+self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[2]/conv-item/div/div[2]/divf/div/p/span"):
                if i.text==name:
                    self.wd.find_element_by_xpath("//*[@id=\"content-pannel\"]/div/div[3]/div/div[1]/ul/li[1]/div/span/input[1]").send_keys(file_path)
                    break
        except:
            raise PDError("File sending failed.")
    def get_latest_time(self,name:str):
        try:
            for i in self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[1]/conv-item/div/div[2]/divf/div/p/span")+self.wd.find_elements_by_xpath("//*[@id=\"sub-menu-pannel\"]/div[1]/div[2]/conv-item/div/div[2]/divf/div/p/span"):
                if i.text==name:
                    return i.find_element_by_xpath("../../../../divf/span").text
        except:
            raise PDError("Get the time failed.")
